import { UploadFilled } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { ElMessageBox } from 'element-plus'

<template>

<el-row gutter="15" style="width: 100%;">
  
  <!-- 固件升级 -->
  <el-col :span="8">
    <el-card v-loading="fwUploadLoading">
      <template #header>
        <div class="card-header">
        <span>固件升级</span>
        </div>
      </template>
      <el-upload
        class="upload-demo"
        drag
        :before-upload="updateFileCheck"
        :on-success="handleSuccess"
        :on-error="handleError"
        :http-request="firmwareUpload"
        :file-list="fileList"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将升级文件拖拽至此上传或者 <em>点击此处上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            升级文件后缀为 *.fw
          </div>
        </template>
      </el-upload>

    </el-card>
  </el-col>

  <!-- 系统工具 -->
  <el-col :span="8">
    <el-card>
      <template #header>
        <div class="card-header">
        <span>设备操作</span>
        </div>
      </template>
      <el-row :gutter="18">
        <el-col :span="6">
        <p>
          <el-button plain @click="logDownload">
            当前日志下载
          </el-button>
        </p>

        <p>
          <el-button plain @click="printLogDownload">
            打印日志下载
          </el-button>
        </p>

        <p>
          <el-button plain @click="logHistoryDownload">
          历史系统日志下载
          </el-button>
        </p>

        <p>
          <el-button plain @click="correctDownload">
          校正数据下载
          </el-button>
        </p>
        <p>
          <el-button plain @click="grayMapDownload">
          灰度曲线下载
          </el-button>
        </p>
        </el-col>
        
        <el-col :span="6">
          <p>
            <el-button type="danger" plain @click="confirmDeviceReset">
              设备重启
            </el-button>
          </p>
          <p>
            <el-button plain @click="dumpstart">
              启动抓包
            </el-button>
          </p>
          <p>
            <el-button plain @click="dumpstop">
              停止抓包
            </el-button>
          </p>
          <p>
            <el-button plain @click="printDownload">
            打印区域下载
            </el-button>
          </p>
          <p>
            <el-button plain @click="grayMapToolDownload">
            灰度曲线调节工具
            </el-button>
          </p>
          
        </el-col>
      </el-row>


      
      
    </el-card>
    
  </el-col>
  
  
</el-row>

<h2></h2>

<el-row gutter="15" style="width: 100%;">

<!-- 固件升级 -->
<el-col :span="8">
  <el-card v-loading="printUploadLoading">
    <template #header>
      <div class="card-header">
      <span>打印固件上传(开发人员使用)</span>
      </div>
    </template>
    <el-upload
      class="upload-demo"
      drag
      :before-upload="printFwCheck"
      :on-success="handleSuccess"
      :on-error="handleError"
      :http-request="printFwUpload"
      :file-list="fileList"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        将升级文件拖拽至此上传或者 <em>点击此处上传</em>
      </div>
    </el-upload>

  </el-card>
</el-col>

<!-- 校正上传 -->
<el-col :span="8">
  <el-card v-loading="correctUploadLoading">
    <template #header>
      <div class="card-header">
      <span>校正数据上传</span>
      </div>
    </template>
    <el-upload
      class="upload-demo"
      drag
      :before-upload="correctCheck"
      :on-success="handleSuccessNoReset"
      :on-error="handleError"
      :http-request="correctUpload"
      :file-list="fileList"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        将升级文件拖拽至此上传或者 <em>点击此处上传</em>
      </div>
    </el-upload>
  </el-card>
</el-col>
</el-row>

<h2></h2>

<!-- 打印图片上传 -->
<el-row gutter="15" style="width: 100%;">
  <el-col :span="8">
    <el-card v-loading="printimageUploadLoading">
    <template #header>
      <div class="card-header">
      <span>打印图片上传</span>
      </div>
    </template>
    <el-upload
      class="upload-demo"
      drag
      :before-upload="printImagetCheck"
      :on-success="handleSuccessNoReset"
      :on-error="handleError"
      :http-request="printImageUpload"
      :file-list="fileList"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        将升级文件拖拽至此上传或者 <em>点击此处上传</em>
      </div>
    </el-upload>
  </el-card>
  </el-col>

  <!-- 灰度曲线上传 -->
  <el-col :span="8">
    <el-card v-loading="grayMapUploading">
    <template #header>
      <div class="card-header">
      <span>灰度曲线上传</span>
      </div>
    </template>
    <el-upload
      class="upload-gray-map"
      drag
      :before-upload="grayMapCheck"
      :on-success="handleSuccessNoReset"
      :on-error="handleError"
      :http-request="grayMapUpload"
      :file-list="fileList"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        将升级文件拖拽至此上传或者 <em>点击此处上传</em>
      </div>
    </el-upload>
  </el-card>
  </el-col>
</el-row>

</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

const fileList = ref([])
const fwUploadLoading = ref(false)
const printUploadLoading = ref(false)
const correctUploadLoading = ref(false)
const printimageUploadLoading = ref(false)
const grayMapUploadLoading = ref(false)



// 确认重启设备
async function confirmDeviceReset() {

  ElMessageBox.alert('确认要重启设备吗', '确认', {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: 'OK',
    callback: (action) => {
      if(action == "confirm")
      {
        try {
          const response = axios.get('/action/device/reset');
          const result = response.data

          if (result.errCode == 0){
            ElMessage.success('操作成功');
          } else {
            ElMessage.error(result.errInfo);
          }

        } catch (error) {
          console.log("重启设备")
        }
      }
    },
  })
}

// 启动抓包
async function dumpstart() {
  const response = axios.get('/action/device/dumpstart')
  .then(response => {
    const result = response.data

    if (result.errCode == 0){
      ElMessage.success('操作成功');
    } else {
      ElMessage.error(result.errInfo);
    }
  })
  .catch(error => {
    console.error('An error occurred!', error);
  });
}

// 启动抓包
async function dumpstop() {
  const response = axios.get('/action/device/dumpstop')
  .then(response => {
    const result = response.data

    if (result.errCode == 0){
      ElMessage.success('操作成功, 请下载当前日志');
    } else {
      ElMessage.error(result.errInfo);
    }
  })
  .catch(error => {
    console.error('An error occurred!', error);
  });
}

// yhl: 返回false就能阻止后面继续
function updateFileCheck(file){
  const isValid = file.name.endsWith('.fw');
  if (!isValid) {
    handleError(new Error('只能上传 .fw 文件'), file)
  }
  
  return isValid;
};
function printFwCheck(file){
  const isValid = (file.name == "rtthread.bin");
  if (!isValid) {
    handleError(new Error('文件名称不正确'), file)
  }
  return isValid;
};
function correctCheck(file){
  // const isValid = (file.name == "correct.bin");
  const isValid = file.name.includes("correct");
  console.log(file.name, isValid)
  if (!isValid) {
    handleError(new Error('文件名称不正确'), file)
  }
  return isValid;
};
function printImagetCheck(file){
  const isValid = (file.name.endsWith(".bmp"));
  if (!isValid) {
    handleError(new Error('文件名称不正确'), file)
  }
  return isValid;
};
function grayMapCheck(file){
  const isValid = (file.name.endsWith(".gm"));
  if (!isValid) {
    handleError(new Error('文件名称不正确'), file)
  }
  return isValid;
};


async function firmwareUpload({ file, onSuccess, onError }) {
  const formData = new FormData();
  formData.append('file', file);
  try {
    fwUploadLoading.value = true
    const response = await axios.post("/action/upload/update-fw", formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },});

    fwUploadLoading.value = false
    const result = response.data

    if (result.errCode == 0) {
      // 如果在途中不报错的话, 就会执行onSuccess
      // onSuccess(result.errInfo, file)
    } else {
      onError(new Error(result.errInfo), file);
    }
  } catch (error) {
    onError(new Error('上传失败'), file);
  }
}

async function printFwUpload({ file, onSuccess, onError }) {
  const formData = new FormData();
  formData.append('file', file);
  try {
    printUploadLoading.value = true
    const response = await axios.post("/action/upload/print-fw", formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },});
    printUploadLoading.value = false

    const result = response.data

    if (result.errCode == 0) {
      // 如果在途中不报错的话, 就会执行onSuccess
      // onSuccess(result.errInfo, file)
    } else {
      onError(new Error(result.errInfo), file);
    }
  } catch (error) {
    onError(new Error('上传失败'), file);
  }
}

async function correctUpload({ file, onSuccess, onError }) {
  const formData = new FormData();
  formData.append('file', file);
  try {
    correctUploadLoading.value = true
    const response = await axios.post("/action/upload/correct", formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },});
    correctUploadLoading.value = false

    const result = response.data

    if (result.errCode == 0) {
      // 如果在途中不报错的话, 就会执行onSuccess
      // onSuccess(result.errInfo, file)
    } else {
      onError(new Error(result.errInfo), file);
    }
  } catch (error) {
    onError(new Error('上传失败'), file);
  }
}

// 打印图片上传
async function printImageUpload({ file, onSuccess, onError }) {
  const formData = new FormData();
  formData.append('file', file);
  try {
    printimageUploadLoading.value = true
    const response = await axios.post("/action/upload/print-image", formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },});
    printimageUploadLoading.value = false

    const result = response.data

    if (result.errCode == 0) {
      // 如果在途中不报错的话, 就会执行onSuccess
      // onSuccess(result.errInfo, file)
    } else {
      onError(new Error(result.errInfo), file);
    }
  } catch (error) {
    onError(new Error('上传失败'), file);
  }
}

// 灰度曲线上传
async function grayMapUpload({ file, onSuccess, onError }) {
  const formData = new FormData();
  formData.append('file', file);
  try {
    grayMapUploadLoading.value = true
    const response = await axios.post("/action/upload/gray-map", formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },});
    grayMapUploadLoading.value = false

    const result = response.data

    if (result.errCode == 0) {
      // 如果在途中不报错的话, 就会执行onSuccess
      // onSuccess(result.errInfo, file)
    } else {
      onError(new Error(result.errInfo), file);
    }
  } catch (error) {
    onError(new Error('上传失败'), file);
  }
}



function handleSuccess(response, file) {
  ElMessage.success('上传成功, 重启设备生效');
}
function handleSuccessNoReset(response, file) {
  ElMessage.success('上传成功');
}

function handleError(error, file) {
  console.log(error)
  ElMessage.error(error.message);
  const index = fileList.value.findIndex(file => file.uid === uid);
  fileList.value.splice(index, 1);
}



function logDownload() {
  const url = '/action/download/log';
  window.location.href = url;
}

function logHistoryDownload() {
  ElMessage.warning('日志打包时间较久, 请耐心等待');
  const url = '/action/download/log-history';
  window.location.href = url;
}
function printLogDownload() {
  const url = '/action/download/print-log';
  window.location.href = url;
}
function correctDownload() {
  const url = '/action/download/correct';
  window.location.href = url;
}
function printDownload() {
  const url = '/action/download/print';
  window.location.href = url;
}
function grayMapDownload() {
  const url = '/action/download/gray-map';
  window.location.href = url;
}
function grayMapToolDownload() {
  const url = '/action/download/gray-map-tool';
  window.location.href = url;
}

</script>










